<?php
class PictureAction extends PublicAction {
    //图片页
	public function index(){
		//$this->assign('jumpUrl',"http://www.baidu.com");
		//$this->error("aaa");
		$cate = M("Category");
		$maps['catepid'] = 1;
		$maps['status'] = 1;
		$cates = $cate->field('cateid,catename')->where($maps)->order('orders asc')->select();
		foreach ($cates as $key => $val){
			$mapss['catepid'] = $val['cateid'];
			$mapss['status'] = 1;
			$catess = $cate->field('cateid,catename')->where($mapss)->order('orders asc')->select();
			if($catess){
				$cates[$key][smcate] = $catess;
			}
		}
		
		//获取图片列表
		
		$pictureview = D('PictureView');
		$picturemodel = M('Picture');
		
		$list=$this->category_search($pictureview);
		foreach($list as $k => $v)
		{
			$list[$k]['url'] = explode(',', $v['url']);
			$hap['pid']=$v['pid'];
			$list[$k]['desc'] = $picturemodel->where($hap)->getField('desc');
		}
		if(!$list){
			$statusx = 1;
		}else{
			$statusx = 0;
		}
		//获取热门推荐图片
		$jiaodianmoedel=M("Jiaodian");
		$hotlist=$jiaodianmoedel->limit("5,5")->order("id asc")->select();
		$this->assign("hotlist",$hotlist);
		//热搜关键词
		$kap['category']=1;
		$searlist = M('Keyword')->where($kap)->order('orders asc')->limit('10')->select();
		$this->assign("searlist",$searlist);
		//专题
		$top['status'] = 1;
		$topic = M('Topic')->where($top)->order('topid desc')->limit('3')->select();
		$this->assign('topic',$topic);
		//获取最近检索词
		$zkeywords=$_SESSION['zkeyword'];
		$this->assign('zkeywords',$zkeywords);
		
		$this->assign('cate',$cates);
		$this->assign('statusx',$statusx);
		$this->assign('list',$list);
		$this->display();
	}
	
	//图片详细页
	public function info(){
		if($_GET['vid']){
			$pic = M('Picture');
			$user = M('User');
			$map['pid'] = $_GET['vid'];
			$info = $pic->where($map)->find();
		if(($info['is_dele']==1)||($info['status'])==0)
			{
				$this->error("此资源已被删除,或未通过审核!");
			}
			$maps['uid'] = $info['uid'];
			$uinfo = $user->field('nickname')->where($maps)->find();
			$info['nickname'] = $uinfo['nickname'];
			$url = explode(',', $info['url']);
			$size = explode(',', $info['size']);
			//$info['size'] = $size[0].",".$size[1];
			$info['size']=$size;
			$info['sizecount']=count($size);
			$area = explode(',', $info['area']);
			//$info['area'] = $area[0].",".$area[1];
			$info['area']=$area;
			$info['areacount']=count($area);
			foreach($url as $ky => $vl){
				if(file_exists('./Public/Uploads/Picture/sy_'.$vl)){
					$url1[$ky]['sy'] = "sy_".$vl;
				}else{
					$url1[$ky]['sy'] = "s_".$vl;
				}
				$url1[$ky]['url'] = $vl;
			}
			$this->assign('url',$url1);
			$this->assign('counturl',count($url));
			$this->assign('zero',0);
			$this->assign('size',$size);
			$this->assign('area',$area);
			$this->assign('info',$info);
			//获取相关图片
			$dap['status']=1;
			$dap['is_dele']=0;
			$dap['cateid']=$info['cateid'];
			$dap['pid']  = array('NEQ',$_GET['vid']);
			$xlist=$pic->where($dap)->limit('0,4')->select();
			foreach ($xlist as $k=>$v)
			{
				$furl=explode(',', $v['url']);
				$xlist[$k]['furl']=$furl[0];
			}
			if($xlist){
				$xsta = 1;
			}else{
				$xsta = 0;
			}
			$this->assign('xsta',$xsta);
			$this->assign('xlist',$xlist);	
			//获取热门图片
			$sap['status']=1;
			$sap['is_dele']=0;
			$rlist=$pic->where($sap)->limit('0,4')->order('point desc')->select();
			foreach ($rlist as $k=>$v)
			{
				$furl=explode(',', $v['url']);
				$rlist[$k]['furl']=$furl[0];
			}
			if($rlist){
				$rsta = 1;
			}else{
				$rsta = 0;
			}
			$this->assign('rsta',$rsta);
			//print_r();
			$this->assign('rlist',$rlist);
			
			//获取资源评论
			import("ORG.Util.Page");
			$comment = M('Comment');
			$user = M('User');
			$qaps['comtype'] = 1;
			$qaps['comstatus'] = 0;
			$qaps['commid'] = $_GET['vid'];
			
			$pgnum = 5;
			if(strtolower($_SERVER['REQUEST_METHOD']) == 'post'){
				if($_POST['pgnum']){
					$pgnum = $_POST['pgnum'];
				}
			}
			$count = $comment->where($qaps)->count();
			$page_com = new Page($count,$pgnum);
			
			$list = $comment->where($qaps)->limit($page_com->firstRow.",".$page_com->listRows)->order('comtime desc')->select();
			foreach($list as $key => $val){
				$mapss['uid'] = $val['comuid'];
				$userinfo = $user->field('nickname,image')->where($mapss)->find();
				$list[$key]['nickname'] = $userinfo['nickname'];
				if($userinfo['image']){
					$list[$key]['image'] = $userinfo['image'];
				}else{
					$list[$key]['image'] = "per_img.jpg";
				}
			}
			 $this->assign('count',$count);
			$this->assign("page_com",$page_com->show());
           $this->assign('list',$list);
		//获取当前积分 
		if(session(C('USER_AUTH_KEY')) || session(C('ADMIN_AUTH_KEY')))
		{	
		$uid=getUserInfo('uid',false);
	   //$uid=getUserInfo('uid');
	   $found=M('User')->where("`uid`=$uid")->field('score')->find();
	   $score=$found['score'];
       $this->assign('prescore',$score);
       $this->assign('isLogin',1);
		}
		//获取当前位置
			$hap['cateid']=$info['cateid'];
			$catefory_model=M('Category');
			$catefory=$catefory_model->where($hap)->find();
			$cate=$catefory['catename'];
			if($catefory['catepid']!=2)
			{
				$rap['cateid']=$catefory['catepid'];
				$erjicate=$catefory_model->where($rap)->find();
				$erjicatename=$erjicate['catename'];
			}
			$this->assign("erjicate",$erjicatename);
			$this->assign("erjicateid",$catefory['catepid']);
			$this->assign("cate",$cate);
	   $this->display();
		}else{
			
		}
	}
	
    //图片上传页面
	public function upload(){
		header('Content-Type:text/html;charset=utf8');
		if(!session(C('USER_AUTH_KEY')) && !session(C('ADMIN_AUTH_KEY')))
		{
			$this->redirect('User/login');
		}else{
			$uid=getUserInfo('uid');
	   		$basic=M('User')->find($uid); 
	   		if($basic['status'] == 2){
			  	if(session(C("USER_AUTH_KEY")))
				{
					if(session(C("USER_AUTH_KEY"))){
						session(C("USER_AUTH_KEY"),NULL);	
					}
					cookie(C('USER_AUTH_ACCOUNT'),null,-3600);
					cookie(C('USER_AUTH_PWD'),null,-3600);
				}
				$this->redirect('User/login');
	  		 }
			
			$model=M('Category');
			$map['status'] = 1;
			$map['catepid'] = 1;
			$list=$model->where($map)->select();
			$this->assign('list',$list);
			if($_GET['success']){
				$this->assign('error',$_GET['error']);
				$this->assign('val',$_GET['success']);	
			}else{
				$this->assign('val',0);	
			}
	        $this->display();
		}
	}
	
//图片上传操作
	public function pictureupload() {
        if (!empty($_FILES)) {
	        $files = $_FILES;
	    	$uploadList = uploadsource('-1','jpg,gif,png,jpeg','./Public/Uploads/Picture/',$files,true,'m_,s_','480,140','400,140');
	        if(is_array($uploadList)){
		    	import("ORG.Util.Image");
		        //给m_缩略图添加水印, Image::water('原文件名','水印图片地址')
		        $num = count($uploadList);
		        $str = "";
		        $size = "";
		        $area = "";
		        for ( $i=0; $i<$num; $i++){
		        	$info = Image::getImageInfo($uploadList[$i]['savepath'] . $uploadList[$i]['savename']);
			        Image::water($uploadList[$i]['savepath'].'m_'.$uploadList[$i]['savename'], './Public/Images/logo.jpg', $uploadList[$i]['savepath'] .'sy_' . $uploadList[$i]['savename'], 50);
			        $m = $i+1;
			        if ($info[size] < 1048576){
			        	$info[size] = ceil($info[size]/1024) . "KB";
			        }else{
			        	$info[size] = round(($info[size]/1048576),1) . "M";
			        }
			        if($m<$num){
			        	$size .= $info[size].",";
			        	$area .= $info[width] . "x" . $info[height] . ",";
			        	$str .= $uploadList[$i]['savename'].",";
			        }else{
			        	$size .= $info[size];
			        	$area .= $info[width] . "x" . $info[height];
			        	$str .= $uploadList[$i]['savename'];
			        }
		        }
		        $_POST['size'] = $size;
		        $_POST['area'] = $area;
		        $_POST['url'] = $str;
	        }else{
	        	 $this->error($uploadList);
	        }
	        
	        $model = D('Picture');
	        //保存当前数据对象
	        $data = $_POST;
	        $data['size'] = $_POST['size'];
		    $data['area'] = $_POST['area'];
	        $data['url'] = $_POST['url'];
	         if($model->create($data))
			{
		        $list = $model->add();
		        if ($list !== false) {
		        	$map['pid'] = $list;
		        	$datas['code'] = 'P'.$list;
		        	$lists = $model->where($map)->save($datas);
		            $this->redirect('Picture/upload',array('success'=>2));
		        } else {
		        	$picurl = explode(',', $_POST['url']);
		        	$num = count($picurl);
		        	 for ( $i=0; $i<$num; $i++){
		        	 	unlink('./Public/Uploads/Picture/'.$picurl[$i]);
		        	 	unlink('./Public/Uploads/Picture/m_'.$picurl[$i]);
		        	 	unlink('./Public/Uploads/Picture/s_'.$picurl[$i]);
		        	 	unlink('./Public/Uploads/Picture/sy_'.$picurl[$i]);
		        	 }
		            $this->redirect('Picture/upload',array('success'=>1));
		        }
			}else{
					$picurl = explode(',', $_POST['url']);
		        	$num = count($picurl);
		        	 for ( $i=0; $i<$num; $i++){
		        	 	unlink('./Public/Uploads/Picture/'.$picurl[$i]);
		        	 	unlink('./Public/Uploads/Picture/m_'.$picurl[$i]);
		        	 	unlink('./Public/Uploads/Picture/s_'.$picurl[$i]);
		        	 	unlink('./Public/Uploads/Picture/sy_'.$picurl[$i]);
		        	 }
				$this->redirect('Picture/upload',array('success'=>1,'error'=>$model->getError()));
			}
        }else{
        	 $this->redirect('Picture/upload',array('success'=>1,'error'=>$model->getError()));
        }
    }
    
	
    /**
     * 下载
     * @author 沈威
     * @tel 15005164276
     * @email 403382132@qq.com
     * Enter description here ...
     */
	public function picturedownload(){
	if(!session(C('USER_AUTH_KEY')) && !session(C('ADMIN_AUTH_KEY'))) $this->redirect('User/login');
		$uid=getUserInfo('uid');
   		$basic=M('User')->find($uid); 
   		if($basic['status'] == 2){
		  	if(session(C("USER_AUTH_KEY")))
			{
				if(session(C("USER_AUTH_KEY"))){
					session(C("USER_AUTH_KEY"),NULL);	
				}
				cookie(C('USER_AUTH_ACCOUNT'),null,-3600);
				cookie(C('USER_AUTH_PWD'),null,-3600);
			}
			echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head>";
  			echo "<body><script>alert('您的帐号已被禁用');history.go(-1)</script></body></html>";
  			exit;
  		 }
	if($_POST){
	  	if($_POST['prescore']<$_POST['score'])
	  	{
	  		echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head>";
	  		echo "<body><script>alert('下载失败,您的积分不足');history.go(-1)</script></body></html>";
	  	}
	  	else
	  	{
	  		$count=$_POST['count'];
		  $pid=$_POST['pid'];
	      $title=$_POST['title'];
	  	  $file_dir="./Public/Uploads/Picture/";
	  	  $picture=M('Picture')->where("pid=$pid")->find();
	  	  $url = explode(',', $_POST['url']);
		  $file_name=$url[$count];
		  $score='-'.$_POST['score'];
		  $addscore=$_POST['score'];
		  $code=$_POST['code'];
		  $this->assign('prescore',$_POST['prescore']);
		  $reason="下载'".$title."'";
		  $addreason="'".$title."'被下载";
	      $uid=getUserInfo('uid',false);
		  $msg=M('Picture')->field('uid')->find($pid);
		  $adduid=$msg['uid'];
		  $map=array('uid'=>$uid,'code'=>$code);
		  $record=M('Score')->where($map)->find();
		  if(download($file_dir,$file_name,$title))
		  {
		      M('Picture')->where("pid=$pid")->setInc('point');
		      if($_POST['once']==1)
		      {
				  if(!in_array($code,$record))
				  {
					  income($uid,$score,$reason,$code);
					  income($adduid,$addscore,$addreason,$code);
		          }
		      }
		  }
		  else 
		  {
		  	 echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head>";
		  	echo "<body><script>alert('下载失败,暂无可下载的水印图片');history.go(-1)</script></body></html>";
		  }
	  	}
	 }
   }
    
   
	//验证码
	public function verify(){
    	import("ORG.Util.Image");	
		Image::buildImageVerify();
	}
	
	//显示资源库下的分类
	public function showsid(){
	    if(!session(C('USER_AUTH_KEY')) && !session(C('ADMIN_AUTH_KEY')))
		$this->redirect('User/login');
		$pid = $_POST['pid'];
		if($pid){
			$map['catepid'] = $pid;
			$map['status'] = 1;
			$resl = M('Category')->where($map)->select();
			if($resl){
				$res = "<option value='0' selected >选择分类</option>";
				foreach ($resl as $key => $value){
					$res .= "<option value='". $value['cateid'] ."'  name='cateid'>" . $value['catename'] . "</option>";
				}
				$res="<select name='cateid' id='cateid' class='cateid' style='width:145px;'>".$res."</select>";
				echo $res;
			}else{
				//$res = "<option value='0' selected >新建分类</option>";
				echo 0;
			}
		}else{
			echo 0;
		}
	}
	
	//发表评论
	public function fbcomment(){
		$uid=getUserInfo('uid');
   		$basic=M('User')->find($uid); 
   		if($basic['status'] == 2){
		  	if(session(C("USER_AUTH_KEY")))
			{
				if(session(C("USER_AUTH_KEY"))){
					session(C("USER_AUTH_KEY"),NULL);	
				}
				cookie(C('USER_AUTH_ACCOUNT'),null,-3600);
				cookie(C('USER_AUTH_PWD'),null,-3600);
			}
			echo "您已被禁用！";
			exit;
  		 }
		
		if(getUserInfo('uid')){
			$cond = $_POST;
			$cond['comuid'] = getUserInfo('uid');
			$cond['_column'] = array('comtype','comcontent','commid','commname','comuid');
			foreach ($cond['_column'] as $one) $data[$one] = trim($cond[$one]);
			$model = D('Comment');
			if($model->create($data))
			{
				if(($comid = $model->add())!= false){
					echo "评论成功，审核通过后可显示。";
				}else{
					echo "评论失败";
				}
			}else{
				echo $model->getError();
			}
		}else{
			echo "登录后才能发表评论";
		}
	} 
	
	//检验验证码
	public function checkverify(){
	    if(!session(C('USER_AUTH_KEY')) && !session(C('ADMIN_AUTH_KEY')))
		$this->redirect('User/login');
		$val=md5($_POST['val']);
		if($val){
		 if($_SESSION['verify'] !=$val) echo 1;
		 else echo 0;
		}
	}
	
	/**
	 * 收藏
	 * @author 沈威
	 * @tel 15005164276
	 * @email 403382132@qq.com
	 * Enter description here ...
	 */
	public function favorite()
	{
		
		if(!session(C('USER_AUTH_KEY')) && !session(C('ADMIN_AUTH_KEY')))
		{
			$this->redirect('User/login');
		}
		else 
		{
			$uid=getUserInfo('uid');
	   		$basic=M('User')->find($uid); 
	   		if($basic['status'] == 2){
			  	if(session(C("USER_AUTH_KEY")))
				{
					if(session(C("USER_AUTH_KEY"))){
						session(C("USER_AUTH_KEY"),NULL);	
					}
					cookie(C('USER_AUTH_ACCOUNT'),null,-3600);
					cookie(C('USER_AUTH_PWD'),null,-3600);
				}
				echo "您已被禁用！";
				exit;
	  		 }
			$type=$_POST['type'];
			$vid=$_POST['vid'];
			$name=$_POST['name'];
			$favoritemodel=M('Favorite');
			$uid=getUserInfo('uid',false);
			$map['uid'] = $uid;
			$map['favid'] = $vid;
			$map['fatype']=$type;
			if($favoritemodel->where($map)->find()){
				echo "已存在收藏中！";
			}else{
				$data['uid']=$uid;
				$data['fatype']=$type;
				$data['favid']=$vid;
				$data['favname']=$name;
				$favoritemodel->add($data);
				echo "已收藏！";
			}
			//echo $favoritemodel->getLastSql();
		}
	}
}